/**
 * TestOpenSocial This JavaScript file is for Canvas view.
 */

// maintain a count
var count = 0;

var start = 0;
var limit = 50;
var page = 1;
var arrFriends = []; // array of friends to be invited
var viewerName = ''; // name of viewer

function init() {
    // TODO: Write the code for initializing.
    fetchPeople(start, limit);
}

// TODO: Write the code for Canvas view.


function fetchPeople(nStart, nCount) {
    start = nStart;
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
    // id specification
    var params = {};
    params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
    params[opensocial.IdSpec.Field.GROUP_ID] = 'FRIENDS';
    var idSpec = opensocial.newIdSpec(params);
    // options
    var opt_param = {};
    opt_param[opensocial.DataRequest.PeopleRequestFields.FIRST] = nStart;
    opt_param[opensocial.DataRequest.PeopleRequestFields.MAX] = nCount;
    req.add(req.newFetchPeopleRequest(idSpec, opt_param), 'friends');
    // send request with an handler
    req.send(onLoadResponse);
}

function onLoadResponse(data) {
    try {
        // get viewer object
        var viewer = data.get('viewer').getData();
        // show viewer name
        viewerName = viewer.getDisplayName();
        document.getElementById('viewer').innerHTML = 'Hello, ' + viewerName + ', your friends are,';
        // get friends data
        var friends = data.get('friends').getData();
        document.getElementById('friends').innerHTML = '';

        var pageControls = '';
        var localcount = 0;
        var inviteControls = '';

        var friends_html = '';

        friends_html += '<table border="0" cellpadding="1" cellspacing="1" width="100%">';
        friends.each(function (person) {
            // / maintain a local count to decide
            localcount++;
            var name = person.getDisplayName();
            var profilePage = person.getField(opensocial.Person.Field.PROFILE_URL);
            var profileThumbnail = person.getField(opensocial.Person.Field.THUMBNAIL_URL);

            var friendDetails = "";
            if (localcount % 2 == 1) {
                friendDetails += "<tr width=\"100%\">";
            }
            friendDetails += "<td align=\"left\" valign=\"center\" bgcolor=\"#fefefe\"> " + "<input type=\"checkbox\" name=\"chk" + localcount + "\" value=\"" + name + "\" onClick=\"updateSelection(this)\">" + name + "</input> <td> ";

            if (localcount % 2 == 0) {
                friendDetails += "</tr>";
            }
            friends_html += friendDetails;

        });
        friends_html = friends_html + '</table>';

        // /////////////////////////////////////////////////////// page controls
        // update page controls
        pageControls = '';
        if (start != 0) {
            // show back button only when start != 0
            pageControls += '<input type=\'button\' class=\'btn\' onClick=\'page=page-1;fetchPeople(start-limit, limit);\' value=\'<\' /> ';
        } else {
            pageControls += '<input type=\'button\' class=\'btn\' disabled value=\'<\' /> ';
        }

        pageControls += 'Page [' + page + ']  ';

        if (localcount == limit) {
            // if count matches, show next control
            // Problem: may show an extra button when pagination is exact
            pageControls += '<input type=\'button\' class=\'btn\' onClick=\'page=page+1;fetchPeople(start+limit, limit);\' value=\'>\' /> ';
        } else {
            pageControls += '<input type=\'button\' class=\'btn\' disabled value=\'>\' /> ';
        }

        inviteControls = '<input type="button" onClick="alert(arrFriends.toSource());" value="Show Selection" />';
        inviteControls += '<input type="button" onClick="inviteAll()" value="Invite" />';

    } catch (err) {
        alert(err.description);
    }
    document.getElementById('friends').innerHTML = pageControls;
    document.getElementById('friends').innerHTML += friends_html;
    document.getElementById('friends').innerHTML += inviteControls;

    gadgets.window.adjustHeight();
}

function updateSelection(checkBox) {
    try {
        if (checkBox.checked) {
            alert(checkBox.value + ' will be added');
            // add it into array
            arrFriends.push(checkBox.value);
        } else {
            alert(checkBox.value + ' will be REMOVED');
            // remove that from friends
            var index = arrFriends.indexOf(checkBox.value);
            if (index != -1) {
                arrFriends.splice(index, 1);
            }
        }
    } catch (err) {
        alert(err.description);
    }

}

function inviteAll() {
    alert("invitation sending to: " + arrFriends);
    try {
        var reason_body = viewerName + " is inviting you to use the FriendInvite Applciation!";
        var reason_message = opensocial.newMessage(reason_body);
        // send invitation, result will be dealt in inviteDone function
        opensocial.requestShareApp(
        arrFriends, reason_message, function inviteDone(return_data) {
            if (return_data.hadError() === false) {
                alert("your Invitations has been sent! congratulations!");
            } else {
                alert(" :( error message: " + return_data.getErrorCode());
            }
        });
    } catch (err) {
        alert(err.description);
    }
};